package com.tech.view.panel;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 可以设置背景图片的 JXPanel
 */
public class ImageJPanel extends JPanel {
	private BufferedImage backgroundImage;

	public ImageJPanel() {
	}

	public ImageJPanel(BufferedImage backgroundImage) {
		super();
		this.backgroundImage = backgroundImage;
	}

	public ImageJPanel(boolean isDoubleBuffered) {
		super(isDoubleBuffered);
	}

	public ImageJPanel(LayoutManager layout) {
		super(layout);
	}

	public ImageJPanel(LayoutManager layout, boolean isDoubleBuffered) {
		super(layout, isDoubleBuffered);
	}

	public BufferedImage getBackgroundImage() {
		return backgroundImage;
	}

	public void setBackgroundImage(BufferedImage backgroundImage) {
		this.backgroundImage = backgroundImage;
	}

	@Override
	protected void paintComponent(Graphics g) {
		// 父类这个方法不能丢！如果丢掉，在拖动滚动条时，会绘制上其他图像的重影
		super.paintComponent(g);
		if (backgroundImage != null) {
			Graphics2D g2 = (Graphics2D) g;
			g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			// 这里将图像居中对齐，是避免缩放后的图像由于反射模糊后图像宽度增大导致图像显示偏移
			g.drawImage(backgroundImage, (getWidth() - backgroundImage.getWidth()) / 2, 0, null);
		}
	}
}
